package xmu.crms.config.security;

import io.jsonwebtoken.Claims;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import xmu.crms.util.JwtUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 拦截需要jwt的地方，解析用户名密码是否正确。
 *
 * @author status200
 * @date 2017/12/24
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final Log log = LogFactory.getLog(JwtAuthenticationFilter.class);

    private String tokenHeader = SecurityConstant.JWT_HEADER;

    private String tokenHeaderPrefix = SecurityConstant.JWT_HEADER_PREFIX;

    /**
     * 只要header包含jwt，即可完成认证
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 先获取Authorization头中的String
        String authString = request.getHeader(this.tokenHeader);

        if(authString != null && authString.startsWith(tokenHeaderPrefix)) {
            // 去掉前缀得到jwt
            String authToken = authString.substring(SecurityConstant.JWT_HEADER_PREFIX.length());

            // 获取jwt中的数据
            Claims claims = JwtUtil.getClaimsFromToken(authToken);

            if (claims != null) {

                do {
                    Date expiredTime = claims.get("exp", Date.class);

                    // jwt过期,跳过权限构建
                    if (expiredTime.getTime() <= System.currentTimeMillis()) {
                        break;
                    }

                    // 生成一个user,存放用户的权限，没有数据
                    JwtUser userDetails = new JwtUser();

                    // 构建权限
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    log.info("authenticated user " + claims.get("id") + ", setting security context");

                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                } while (false);
            }
        }

        filterChain.doFilter(request, response);
    }
}
